package java8NewFeatures.stream;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author ldy
 * @data 2022/12/2
 * @description
 */
public class orElseAndorElseGetDemo {

    List<Persion> init(){
        ArrayList<Persion> list = new ArrayList<>();
        list.add(new Persion("张三",18,new Date()));
        list.add(new Persion("李四",19,new Date()));
        list.add(new Persion("王五",20,null));
        list.add(new Persion("韩六",21,new Date()));
        list.add(new Persion("龙七",22,null));
        list.add(new Persion("猪八",23,new Date()));
        return list;
    }
    public void main(String[] args) {
        List<Persion> init = init();


        List<Date> collect = init.stream().map(
                persion -> persion.getDate() != null ? persion.getDate() : new Date()
        ).collect(Collectors.toList());
        //从上面可以看出来，当Optonal的值是空值时，无论orElse还是orElseGet都会执行；而当返回的Optional有值时，orElse会执行，而orElseGet不会执行。
        List<Date> collect1 = init.stream().map(
                persion -> Optional.ofNullable(persion.getDate()).orElse(new Date())
        ).collect(Collectors.toList());
        List<Date> collect2 = init.stream().map(
                persion -> Optional.ofNullable(persion.getDate()).orElseGet(()->new Date())
        ).collect(Collectors.toList());
    }






















    private class Persion {
        private String name;
        private Integer age;
        private Date date;
        Persion(String name,Integer age,Date date){
            this.name=name;
            this.age=age;
            this.date=date;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public Date getDate() {
            return date;
        }

        public void setDate(Date date) {
            this.date = date;
        }
    }
}
